﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Zjs_Shop.Models;
using Zjs_Shop.Models.Database;

namespace Zjs_Shop.Service
{
    public class UserService : IUserService
    {
        //定义数据库上下文
        private readonly ZjsShopContext _db;
        public UserService(ZjsShopContext db)
        {
            _db = db;
        }
        /// <summary>
        /// 根据用户名 从数据库获取用户
        /// </summary>
        /// <returns>用户名</returns>
        //public User GetphoneByphone(string phone)
        //{

        //    return _db.Users.FirstOrDefault(x => x.Phone == phone);

        //}
        /// <summary>
        /// 根据用户名判断用户是否存在
        /// </summary>
        /// <param name="username"></param>
        /// <returns>是或非</returns>
        public bool TfUserphone(string phone)
        {
            return _db.Users.Any(x => x.Phone == phone);
        }
        /// <summary>
        /// 注册 添加新用户
        /// </summary>
        /// <param></param>
        /// <param name="Phone"></param>
        /// <param name="Password"></param>
        /// <returns>用户ID</returns>
        public int Reg(string Phone, string Password)
        {
            //随机数1000-9999
            var salt = new Random().Next(1000, 9999);

            //123456+随机值   “E1ADC3949BA59ABBE56E057F2F883E”  //结果变化
            //222222    "E1xxxxxxxxxxxxxxxxxxxxxxxxxxxx"   //所有的组合记录下来
            //在对密码进行MD5 md5(密码+随机数)

            var md5 = MD5Helper.MD5Encrypt32(Password + salt.ToString());
            var user = new User()
            {

                Phone = Phone,
                Password = md5,

            };
            //上下文.表名.操作方法(需要插入的数据对象)
            _db.Users.Add(user);
            var row = _db.SaveChanges();
            if (row > 0)
            {
                return user.Id;
            }
            return 0;

        }
        /// <summary>
        /// 根据手机号查询用户是否存在
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        public User GetphoneByphone(string phone)
        {
            return _db.Users.FirstOrDefault(x => x.Phone == phone);
        }
        /// <summary>
        /// 修改用户资料
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="Username"></param>
        /// <param name="Email"></param>
        /// <param name="Address"></param>
        /// <returns></returns>
        public string Updatauser(int userId, string Username, string Photo, string Address)
        {
            var user = _db.Users.FirstOrDefault(x => x.Id == userId);


            user.Username = Username;
            user.Photo = Photo;
            user.Address = Address;

            var row = _db.SaveChanges();
            if (row > 0)
            {
                return "更新成功";
            }
            return "更新失败";
        }
        public List<UserCenter> UserCenter(int userid)
        {

            
            var cars = _db.Orders.Where(x => x.UserId == userid);
            int ysend = 0;
            int nsend = 0;
            foreach(var i in cars)
            {
                if (i.Status == "已发货")
                    ysend++;
                if (i.Status == "待发货")
                    nsend++;
            }
            var list = cars.Join(_db.Users, x => x.UserId, y => y.Id, (x, y) => new UserCenter
            {
               Ysend=ysend,
               Nsend=nsend,
               Username=y.Username

            }).ToList();
            return list;
        }
        /// <summary>
        /// 新增商品
        /// </summary>
        /// <param name="name"></param>
        /// <param name="price"></param>
        /// <param name="description"></param>
        /// <param name="category_id"></param>
        /// <returns></returns>
        public int Addpro(string name, decimal price, string description, int category_id, int stock)
        {
            var product = new Product()
            {
                Name = name,
                Price = price,
                Description = description,
                CategoryId = category_id,
                Stock = stock

            };
            _db.Products.Add(product);
            var row = _db.SaveChanges();
            if (row > 0)
            {
                return product.Id;
            }
            return 0;
        }
        /// <summary>
        /// 更新数据
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="name"></param>
        /// <param name="price"></param>
        /// <param name="description"></param>
        /// <param name="category_id"></param>
        /// <returns></returns>
        public string Updatepro(int Id, string name, decimal price, string description, int category_id, int stock)
        {
            var product = _db.Products.FirstOrDefault(x => x.Id == Id);
            if (product == null)
                return "没有该商品";

            product.Name = name;
            product.Price = price;
            product.Description = description;
            product.CategoryId = category_id;
            product.Stock = stock;
            var row = _db.SaveChanges();
            if (row > 0)
            {
                return "更新成功";
            }
            return "更新失败";

        }
        /// <summary>
        /// Id查询
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public Product GetProducts(int Id)
        {

            return _db.Products.FirstOrDefault(x => x.Id == Id);


        }
        /// <summary>
        /// 删除shangp
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string DelProduct(int id)
        {
            var product = _db.Products.FirstOrDefault(x => x.Id == id);
            if (product == null)
                return "没有该商品";

            _db.Products.Remove(product);
            var row = _db.SaveChanges();
            if (row > 0)
            {
                return "删除成功";
            }
            return "删除失败";
        }
        /// <summary>
        /// 新增分类
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public string AddCategory(int CategoryId, string name)
        {
            var category = new Category()
            {
                CategoryId = CategoryId,
                Name = name
            };
            _db.Categories.Add(category);
            var row = _db.SaveChanges();
            if (row > 0)
            {
                return "新增成功";
            }
            return "新增失败";
        }
        /// <summary>
        /// 更新分类
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="CategoryId"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public string UpdateCategory(int Id, int CategoryId, string name)
        {
            var category = _db.Categories.FirstOrDefault(x => x.Id == Id);
            if (category == null)
                return "没有该分类";

            category.Id = CategoryId;
            category.Name = name;

            var row = _db.SaveChanges();
            if (row > 0)
            {
                return "更新成功";
            }
            return "更新失败";

        }
        /// <summary>
        /// 查询分类
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public Category GetCategory(int Id)
        {
            return _db.Categories.FirstOrDefault(x => x.Id == Id);

        }
        /// <summary>
        /// 删除分类
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string DelCategory(int id)
        {
            var category = _db.Categories.FirstOrDefault(x => x.Id == id);
            if (category == null)
                return "没有该商品";

            _db.Categories.Remove(category);
            var row = _db.SaveChanges();
            if (row > 0)
            {
                return "删除成功";
            }
            return "删除失败";
        }
        public GetProResponse GetGoodShow(int CateId, string Keyword, int PageIndex, int PageSize)
        {
            //req.cateId== Good.CateId                1                                   null

            //固定条件查询
            var good = _db.Products.Where(x => x.CategoryId == CateId);
            //根据条件查询
            if (!string.IsNullOrEmpty(Keyword))
            {
                good = good.Where(x => x.Description.Contains(Keyword));
            }
            //查询该条件下的总数
            
            var total = good.Count();
            var list = good
                // 9
                //1 0
                //2 (PageIndex-1)*PageSize
                //排序 根据价格倒叙
                .OrderByDescending(x => x.Price)
                //跳过
                .Skip((PageIndex - 1) * PageSize)
                //取前几条
                .Take(PageSize)
                //形成自定义类
                .Select(x => new ProShowModel
                {
                    ProId = x.Id,
                    Title = x.Description
                   
                })
                .ToList();
            ///构造返回对象
            var response = new GetProResponse()
            {
                List = list,
                Total = total
            };
            return response;
        }
        /// <summary>
        /// 加入购物车
        /// </summary>
        /// <param name="product_id"></param>
        /// <param name="quantity"></param>
        /// <returns></returns>
        public string AddCar(int userid, int product_id)
        {
            var Pro = _db.Products.FirstOrDefault(x => x.Id == product_id);
            var car = _db.Carts.FirstOrDefault(x => x.ProductId == product_id);
            if (car == null)//如果购物车没该商品 执行添加
            {
                var cart = new Cart()
                {
                    ProductId = product_id,
                    UserId = userid,
                    Quantity = 1,
                    Oprice = Pro.Price


                };
                _db.Carts.Add(cart);
                var row = _db.SaveChanges();
                if (row > 0)
                {

                    return "加入成功";
                }
                return "加入失败";
            }
            else
            {
                //如果购物车有该商品 执行数量加一 总价=当前数量*单价
                car.Quantity++;
                car.Oprice = Pro.Price * car.Quantity;
                var rows = _db.SaveChanges();
                if (rows > 0)
                {

                    return "加入成功";
                }
                return "加入失败";
            }



        }
       

        /// <summary>
        /// 减少购物车
        /// </summary>
        /// <param name="product_id"></param>
        /// <returns></returns>
        public string UpdataCar(int product_id)
        {
            var car = _db.Carts.FirstOrDefault(x => x.ProductId == product_id);
            if (car == null)
                return "没有该商品";
            car.Quantity--;
            var row = _db.SaveChanges();
            if (row > 0)
            {
                return "减少成功";
            }
            return "减少失败";
        }
        /// <summary>
        /// 删除购物车
        /// </summary>
        /// <param name="product_id"></param>
        /// <returns></returns>
        public string DelCar(int product_id)
        {
            var car = _db.Carts.FirstOrDefault(x => x.ProductId == product_id);
            if (car == null)
                return "没有该商品";

            _db.Carts.Remove(car);
            var row = _db.SaveChanges();
            if (row > 0)
            {
                return "删除成功";
            }
            return "删除失败";
        }
        /// <summary>
        /// 查询购物车
        /// </summary>
        /// <returns></returns>
        public List<ModelCar> Getcar(int userid)
        {
            var car = _db.Carts.Where(x => x.UserId == userid);
            var list = car.Join(_db.Products, x => x.ProductId, y => y.Id, (x, y) => new ModelCar
            {
                Name = y.Name,
                ProductId = x.Id,
                Quantity = x.Quantity,
                Price = y.Price,
                OPrice = (decimal)(y.Price * x.Quantity)

            }).ToList();
            return list;

        }
      
        public string AddOrder(int userid)
        {
            var cars = _db.Carts.Where(x => x.UserId == userid).ToList();
            var car = _db.Carts.FirstOrDefault(x => x.UserId == userid);

            if (car == null)
                return "你未下单任何东西";

            var order = new Order()
            {
                UserId = userid,
                OrderDate = DateTime.Now,
                TotalAmount = car.Oprice,
                Status = "待发货",
                ExpCom="无",
                ExpressId="无"
            };
            _db.Orders.Add(order);

            var row = _db.SaveChanges();
            if (row <= 0)
                return "支付失败";


            //如果表有多条数据 循环加入detail表
            var details = new List<OrderDetail>();
            foreach (var i in cars)
            {
                var Pro = _db.Products.FirstOrDefault(x => x.Id == car.ProductId);
                if (Pro == null)
                    return "你未下单任何东西";

                var orderdetail = new OrderDetail()
                {
                    ProductId = car.ProductId,
                    OrderId = order.Id,
                    Quantity = car.Quantity,
                    Price = Pro.Price
                };
                _db.OrderDetails.AddRange(orderdetail);
                details.Add(orderdetail);
                Pro.Stock -= car.Quantity;
            }

            var rows = _db.SaveChanges();
            if (rows <= 0)
            {
                return "支付失败";
            }
            // 清空用户购物车并返回成功
            _db.Carts.RemoveRange(car);
            row = _db.SaveChanges();
            return "支付成功";

        }
        public List<ModelOrder> modelOrders(int userid)
        {
            var Order = _db.Orders.Where(x => x.UserId == userid);
            var list = Order.Join(_db.OrderDetails, x => x.Id, y => y.OrderId, (x, y) => new { Order = x, OrderDetails = y })
                .Join(_db.Products, xy => xy.OrderDetails.ProductId, z => z.Id, (xy, z) => new ModelOrder
                {

                    Name = z.Name,
                    Quantity=xy.OrderDetails.Quantity,
                    TotalAmount = xy.Order.TotalAmount,
                    OrderDate = DateTime.Now,
                    Status = xy.Order.Status
                }).ToList();
            return list;

        }
        public List<ModelBsg> ModelBsg()
        {
            var Order = _db.Orders.AsQueryable();
            var list = Order.Join(_db.OrderDetails, x => x.Id, y => y.OrderId, (x, y) => new { Order = x, OrderDetails = y })
                .Join(_db.Products, xy => xy.OrderDetails.ProductId, z => z.Id, (xy, z) => new ModelBsg
                {

                    OrderId=xy.OrderDetails.OrderId,
                    UserId=xy.Order.UserId,
                    TotalAmount=xy.Order.TotalAmount,
                    Name=z.Name
                }).ToList();
            return list;

        }
        public string BsgSend(int id, string expcom,string expressid)
        {
            var Order = _db.Orders.FirstOrDefault(x => x.Id == id);
            if (Order == null)
                return "未找到该订单";

            Order.ExpCom = expcom;
            Order.ExpressId = expressid;
            Order.Status = "已发货";

            var row = _db.SaveChanges();
            if (row > 0)
            {
                return "发货成功";
            }
            return "发货失败";
        }
    }
}
